//
//  RadioTracksViewController.m
//  CatMusic
//
//  Created by dllo on 15/4/24.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "RadioTracksViewController.h"
#import "NetWorkingTool.h"
#import "RadioListTableViewCell.h"
#import "BaseTableViewCell.h"
#import "RadioListViewController.h"
#import "UIImageView+WebCache.h"
#import "NightMode.h"
#import "BaseModel.h"
#import "MusicPlayViewController.h"
#import "AFNetworkReachabilityManager.h"
#import "MJRefresh.h"
#import "UMSocial.h"
#import "PlayerSingleton.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface RadioTracksViewController ()<UITableViewDataSource, UITableViewDelegate , UIActionSheetDelegate>

@property(nonatomic,retain)NSMutableDictionary *dicAlbum;
@property(nonatomic,retain)NSMutableDictionary *dicTracks;
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)BaseTableViewCell *cell;
@property(nonatomic , retain)NSMutableArray *modelArr;

@property (nonatomic , assign)NSInteger number;

@property(nonatomic, retain)UIButton *button;
@end

@implementation RadioTracksViewController

-(void)dealloc
{
    [_button release];
    [_cell release];
    [_modelArr release];
    [_dicAlbum release];
    [_dicTracks release];
    [_tableView release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dicAlbum = [NSMutableDictionary dictionary];
        self.dicTracks = [NSMutableDictionary dictionary];
        self.modelArr = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor whiteColor];
    
    // 夜间模式判断
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setLightDayModel) name:@"LightDayNSNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setNightDayModel) name:@"NightDayNSNotification" object:nil];
    
    if ([NightMode shareNightMode].isNight) {
        [self setNightDayModel];
    } else {
        [self setLightDayModel];
    }

 
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 70) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tag = 10000;
    [self.view addSubview:self.tableView];
    //    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [self creatData];
    
    
    
#pragma mark - 判断网络状态    AFN
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                NSLog(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                NSLog(@"没有网络(断网)");
                [self alertViewCancel];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                NSLog(@"手机自带网络");
                [self alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN];
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                NSLog(@"WIFI");
               [self creatData];
                [self tableViewRefresh];
                break;
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];
 
}


// 下拉刷新
- (void)tableViewRefresh
{
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        // 延迟加载数据，2秒后才调用
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            
            // 结束刷新
            [self.tableView.header endRefreshing];
        });
        
    }];
}



- (void)alertViewCancel
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络断开连接" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
    [alert show];
}

- (void)alertViewCancelAFNetworkReachabilityStatusReachableViaWWAN
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"手机自带网络" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil];
    [alert show];
}

- (void)creatData
{
    [NetWorkingTool netWorkingToolStr:self.url block:^(id result) {
        NSMutableDictionary *dic = result;
        self.dicAlbum = [dic objectForKey:@"album"];
        self.dicTracks = [dic objectForKey:@"tracks"];
        NSMutableArray *arr =[self.dicTracks objectForKey:@"list"];
        for (NSInteger i = 0; i < arr.count ; i++) {
            BaseModel *baseMo = [[BaseModel alloc]init];
            baseMo.songe_url = [self.dicTracks objectForKey:@"list"][i][@"playUrl64"];
            baseMo.song_name = [self.dicTracks objectForKey:@"list"][i][@"title"];
            baseMo.singer_name = [self.dicTracks objectForKey:@"list"][i][@"nickname"];
            [self.modelArr addObject:baseMo];
            [baseMo release];
        }
        
        [self.tableView reloadData];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray *arr = [self.dicTracks objectForKey:@"list"];
    return arr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
//        if ([NightMode shareNightMode].isNight) {
//            [self setNightDayModel];
//        } else {
//            [self setLightDayModel];
//        }
        //        static NSString *reuse = @"reuseInfo";
        RadioListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseInfo"];
        if (!cell) {
            cell = [[RadioListTableViewCell alloc] init];
        }
        
        NSString *pic = [self.dicAlbum objectForKey:@"coverWebLarge"];
        NSURL *pic_url = [NSURL URLWithString:pic];
        [cell.picView sd_setImageWithURL:pic_url];
        //        cell.tracksInfo.text = [self.dicAlbum objectForKey:@"intro"];
        //        cell.tracksInfo.text = @"111";
        return cell;
    }
    else
    {
        
//        if ([NightMode shareNightMode].isNight) {
//            [self setNightDayModel];
//        } else {
//            [self setLightDayModel];
//        }
//        

        
        //        static NSString *reuse = @"reuseList";
        self.cell = [tableView dequeueReusableCellWithIdentifier:@"reuseList"];
        if (!self.cell) {
            self.cell = [[BaseTableViewCell alloc] init];
        }
        //        for (NSInteger i = 0; i < [[self.dicTracks objectForKey:@"list"] count]; i++) {
        self.cell.BaseSingerNameLabel.text = [self.dicTracks objectForKey:@"list"][indexPath.row][@"nickname"];
        self.cell.BaseSongNameLabel.text = [self.dicTracks objectForKey:@"list"][indexPath.row][@"title"];
        self.cell.baseNumberLabel.text = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
        // 在行中加入button
        self.button = [UIButton buttonWithType:UIButtonTypeSystem];
        self.button.frame = CGRectMake(WIDTH / 375 * 340, HEIGHT / 667 * 25, WIDTH / 375 * 30, HEIGHT / 667 * 30);
        [self.button setTitle:@"+" forState:UIControlStateNormal];
        [self.button.titleLabel setFont:[UIFont systemFontOfSize:30]];
        self.button.tag = indexPath.row + 1000;
//        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-xiangyou"] forState:UIControlStateNormal];
        [self.button addTarget:self action:@selector(cellButtonAction:) forControlEvents:UIControlEventTouchUpInside];
//        button.backgroundColor = [UIColor cyanColor];
        [self.cell.contentView addSubview:self.button];
        return self.cell;
    }
}

#pragma mark  cell button 点击事件
- (void)cellButtonAction:(UIButton *)button{
    self.number = button.tag - 1000;
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"列表" delegate:self cancelButtonTitle:@"Bye Bye" destructiveButtonTitle:@"继续" otherButtonTitles:@"收藏" , @"分享",@"清除缓存" , nil];
    [actionSheet showInView:self.view];
    [actionSheet release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    NSArray *sandBox = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *sandBoxPath = [sandBox lastObject];
    NSFileManager *bigFileManager = [NSFileManager defaultManager];
    NSString *bigFileManagerPath = [sandBoxPath stringByAppendingPathComponent:@"collect"];
    [bigFileManager createDirectoryAtPath:bigFileManagerPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSString *songName =  [self.dicTracks objectForKey:@"list"][self.number][@"title"];
    NSString *songNameEncoding = [songName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if (buttonIndex == 0) {
        NSLog(@"0");
    }
    else if (buttonIndex == 1){
            NSString *playModelPath = [bigFileManagerPath stringByAppendingFormat:@"/%@.plist" , songNameEncoding];
            [NSKeyedArchiver archiveRootObject:self.modelArr[self.number] toFile:playModelPath];
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil, nil];
            [alert show];

    }
    else if (buttonIndex == 2){
        //注意：分享到微信好友、微信朋友圈、微信收藏、QQ空间、QQ好友、来往好友、来往朋友圈、易信好友、易信朋友圈、Facebook、Twitter、Instagram等平台需要参考各自的集成方法
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"5541c88ce0f55a9452003a17"
                                          shareText:@"分享来自CatMusic:"
                                         shareImage:[UIImage imageNamed:@"icon.png"]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,nil]
                                           delegate:nil];
        
    }
    else if (buttonIndex == 3){
        //        BOOL result = [bigFileManager removeItemAtPath:bigFileManagerPath error:nil];
        BOOL result = 1;
        if (result == 1) {
            UIAlertView *clearCaches = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定清除缓存???" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
            [clearCaches show];
            [clearCaches release];
        }else{
            NSLog(@"删除失败");
        }
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        
        [self clearButton];
    }
}

- (void)clearButton
{
    //    UIButton *button = (UIButton *)sender;
    //    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    //    [button setTitle:@"正在清理中..." forState:UIControlStateNormal];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    
    //    NSString *str = [NSString stringWithFormat:@"缓存已清除%.1fM", [self folderSizeAtPath:path]];
    
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    for (NSString *p in files) {
        NSError *error;
        NSString *Path = [path stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
        }
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"缓存已清除" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
        return 300;
    else
        return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicPlayViewController * musicPlay = [[MusicPlayViewController alloc]init];
    
    NSMutableArray *arr = [self.dicTracks objectForKey:@"list"];
    NSMutableArray *radioArr = [NSMutableArray array];
    for (NSInteger i = 0; i < arr.count; i++) {
        BaseModel *baseMo = [[BaseModel alloc]init];
        baseMo.songe_url = [self.dicTracks objectForKey:@"list"][i][@"playUrl64"];
        baseMo.song_name = [self.dicTracks objectForKey:@"list"][i][@"title"];
        baseMo.singer_name = [self.dicTracks objectForKey:@"list"][i][@"nickname"];
        baseMo.pic_url = [self.dicTracks objectForKey:@"list"][i][@"coverLarge"];
        [radioArr addObject:baseMo];
    }
    musicPlay.indexPath = indexPath.row;
    musicPlay.modelArr = radioArr;
    [self.navigationController pushViewController:musicPlay animated:YES];
    [musicPlay release];
    
    
}



- (void)setLightDayModel
{
    [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.cell.backgroundColor = [UIColor whiteColor];
    self.cell.baseNumberLabel.textColor = [UIColor blackColor];
    self.cell.BaseSingerNameLabel.textColor = [UIColor blackColor];
    self.cell.BaseSongNameLabel.textColor = [UIColor blackColor];
    self.tabBarController.tabBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:245 / 255.0 green:241/ 255.0 blue:143 / 255.0 alpha:1];//////
    
    UIColor * color = [UIColor blackColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;
    
    
}

- (void)setNightDayModel
{
    [self.button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    self.cell.backgroundColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
    self.cell.baseNumberLabel.textColor = [UIColor whiteColor];
    self.cell.BaseSingerNameLabel.textColor = [UIColor whiteColor];
    self.cell.BaseSongNameLabel.textColor = [UIColor whiteColor];

    self.view.backgroundColor = [UIColor blackColor];
    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:38 / 255.0 green:38/ 255.0 blue:38 / 255.0 alpha:1];
    
      
    UIColor * color = [UIColor whiteColor];
    //这里我们设置的是颜色，还可以设置shadow等，具体可以参见api
    NSDictionary * dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    //大功告成
    self.navigationController.navigationBar.titleTextAttributes = dict;

        
}









- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
